package com.suzhe.ymall.common.interceptor;

import com.suzhe.ymall.common.annotation.ExcludeAuth;
import com.suzhe.ymall.common.exception.AuthorizationException;
import com.suzhe.ymall.common.handler.AuthorizationHander;
import com.suzhe.ymall.common.utils.YMConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author suzhe
 * @date 2019/6/8
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private Map<String,AuthorizationHander> authorizationHanderMap;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthorizationException {

        ExcludeAuth excludeAuth;
        if(handler instanceof HandlerMethod) {
            excludeAuth = ((HandlerMethod) handler).getMethodAnnotation(ExcludeAuth.class);
        }else{
            return true;
        }
        if(excludeAuth != null){//带有该注解的不经过授权处理
            return true;
        }

        String source = request.getHeader(YMConstant.REQUEST_SOURCE);
        AuthorizationHander authorizationHander = authorizationHanderMap.get(source);
        if (authorizationHander == null){
            if(!(handler instanceof HandlerMethod)) {
                return true;
            }
            throw new AuthorizationException("非法请求");
        }
        return authorizationHander.handle(request,response,handler);
    }

}
